import cgi
import datetime
import urllib
import wsgiref.handlers

import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


### MODELS ### 
  
class Users(db.Model):
	email = db.StringProperty()
	
class Categories(db.Model):
	name = db.StringProperty()
	father_id = db.IntegerProperty()
	level = db.IntegerProperty(default=0)
	
	###
	#Desc: Get all category (sort by Father - children)
	#Return: Category array
	#Create: 07/24/12
	###
	@staticmethod
	def get_all(user_email):
		categories = Categories.all().ancestor(user_key(user_email))
		
		#re-sort category  list with order father-child
		categories = categories.fetch(categories.count())
		len_cat = len(categories)
		i = 0
		while i < (len_cat-1):
			j = i+1
			while j < len_cat:
				# j is child of i
				if categories[j].father_id == categories[i].key().id():
					temp_cat = categories[j]
					# remove old child
					del categories[j]
					# insert child to next position of father
					categories.insert(i+1, temp_cat)				
				j += 1
			i += 1
		return categories
	
	
class Items(db.Model):
	category_id = db.IntegerProperty()
	amount = db.FloatProperty()
	date = db.DateProperty()
	type = db.StringProperty()	#in/out
	note = db.StringProperty()
	

def user_key(user_name=None):
  """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
  return db.Key.from_path('User', user_name or 'everybody')